package sslf.com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class FileUpload {

	@RequestMapping(value = "fileUpload2", method = RequestMethod.POST)
	public String upload(HttpServletRequest request) throws IllegalStateException, IOException{
		// 设置上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		
		// 检查form是否带有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)){
			MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest)request;
			Iterator<String> iter = servletRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = servletRequest.getFile(iter.next());
				if (file != null) {  
                    String fileName = "demoUpload" + file.getOriginalFilename();  
                    String path = "D:/" + fileName;  
  
                    File localFile = new File(path);  
                    file.transferTo(localFile);  
                } 
			}
		}
		return "dataSuccess";
	}
}
